const { db, query } = require("../../db/db");
const util = require("util");
const moment = require("moment");
const dayjs = require("dayjs");

async function BuSignIn(req, res) {
  let UserId = Number(req.params.username);
  const Date = req.body.Date;

  const flag = dayjs(Date).isBefore(dayjs().format("YYYY-MM-DD"));

  if (!flag) {
    return res.send({
      Message: "并非可补签日期",
      status: 1,
    });
  }

  //先查询是否已经补签
  const select_sign_in = util.format(
    "Select * from User_Sign_In_Day Where UserId=%s and SignInDate='%s'",
    UserId,
    Date
  );

  const select_sign_in_res = await query(select_sign_in);

  if (select_sign_in_res.length !== 0) {
    return res.send({
      status: 0,
    });
  }

  //先查询是否有补签卡
  const select_user_info = util.format(
    "Select \
    BuCardNum from User Where UserId=%s",
    UserId
  );

  const select_user_info_res = await query(select_user_info);

  if (select_user_info_res[0].BuCardNum == 0) {
    return res.send({
      status: 0,
      NoCardId: 1,
      Messgae: "补签卡已用完",
    });
  }

  const insert_sign_in = util.format(
    "Insert INTO User_Sign_In_Day \
    (UserId,SignInDate,CreateTime) \
    Values(%s,'%s','%s')",
    UserId,
    Date,
    moment().format("YYYY-MM-DD HH:mm:ss")
  );

  await query(insert_sign_in);

  //消耗补签卡
  const update_user_info = util.format(
    "Update User Set BuCardNum=BuCardNum-1 Where UserId=%s",
    UserId
  );

  await query(update_user_info);

  res.send({
    status: 0,
  });
}

module.exports = { BuSignIn };
